package com.qf.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 高圆圆
 * @date 2023/5/30 16:38
 * 定义全局过滤器,解决post提交中文乱码以及响应乱码
 */
@WebFilter("/*")
public class CharacterFilter  implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("全局过滤器初始化完毕");
    }

    //过滤任务
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {

        //ServletRequest/ServletResponse--->HttpServletRequest/HttpServletResponse
        HttpServletRequest request = (HttpServletRequest) servletRequest ;
        HttpServletResponse response = (HttpServletResponse) servletResponse ;


        //获取前端请求方式
        String method = request.getMethod() ;
        if("post".equalsIgnoreCase(method)){
            //解决post提交中文乱码
            request.setCharacterEncoding("utf-8");
        }

        //解决响应乱码
        response.setContentType("text/html;charset=utf-8") ; //文本格式
        response.setContentType("application/json;charset=utf-8") ; //json格式

        //放行
        filterChain.doFilter(request,response);

    }

    @Override
    public void destroy() {
        System.out.println("全局过滤器销毁");
    }
}
